﻿using IM.Easy.Api.AccountManage;
using IM.Easy.AuthorizationServices.IServices;
using IM.Easy.Core.AppContext;
using IM.Easy.Core.Attributes;
using IM.Easy.Core.Filters;
using IM.Easy.Core.Utils;
using IM.Easy.CoreServices.IServices;
using IM.Easy.Entity.System;
using IM.Easy.Infrastructure.Constants;
using IM.Easy.Infrastructure.Query;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.Dtos.User;
using IM.Easy.SystemServices.IServices;
using IM.Easy.SystemServices.Services;
using Mapster;
using Microsoft.AspNetCore.Mvc;

namespace IM.Easy.Api.Controllers.System
{
    /// <summary>
    /// 用户基本资料
    /// </summary>
    [Route("system/user/profile")]
    public class UserProfileController : ControllerBase
    {
        private readonly IUserProfileService _userProfileService;
        private readonly IExternalUserAccountService _externalUserService;
        private readonly IAuthorizationService _authorizationService;
        private readonly IFileResourceService _fileResourceService;
        private readonly AccountService _accountService;

        public UserProfileController(IUserProfileService userProfileService,
            IExternalUserAccountService externalUserService,
            IAuthorizationService authorizationService,
            IFileResourceService fileResourceService,
            AccountService accountService)
        {
            _userProfileService = userProfileService;
            _externalUserService = externalUserService;
            _authorizationService = authorizationService;
            _fileResourceService = fileResourceService;
            _accountService = accountService;
        }

        /// <summary>
        /// 获取账户基本信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Api(Name = "获取账户基本信息")]
        public UserProfile Get()
        {
            var uid = ImApp.User.Id;
            var profile = _userProfileService.Get(uid);
            //var externalAccount = _externalUserService.GetList(s => s.UserId == uid);
            //profile.
            return profile;
        }

        /// <summary>
        /// 获取已第三方绑定账号
        /// </summary>
        [Api(Name = "获取已绑定三方账号")]
        public List<ExternalUserAccount> GetBinds()
        {
            var uid = ImApp.User.Id;
            var externalAccount = _externalUserService.GetList(s => s.UserId == uid);
            return externalAccount;
        }

        /// <summary>
        /// 解绑第三方账号
        /// </summary>
        [HttpDelete]
        [Api(Name = "解绑三方账号")]
        public void UnBind([FromQuery] long bindId)
        {
            var uid = ImApp.User.Id;
            var external = _externalUserService.GetById(bindId);
            if (external.UserId != uid) ExceptionUtils.ThrowBusinessException("解绑失败，异常操作");
            _externalUserService.Unbind(bindId);
        }

        /// <summary>
        /// 通过授权码进行绑定
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="code"></param>
        /// <param name="redirectUrl"></param>
        [HttpPost("bind")]
        public async Task Bind([FromBody] BindUserDto bindUserDto)
        {
            var oauthUser = await _authorizationService.AuthenticateUserAsync(bindUserDto.Code, bindUserDto.Provider, bindUserDto.RedirectUrl);
            var externalUser = _externalUserService.GetSingle(s => s.Provider == oauthUser.Provider && s.ProviderUserId == oauthUser.Id);
            var uid = ImApp.User.Id;
            var user = _userProfileService.GetById(uid);
            externalUser ??= oauthUser.Adapt<ExternalUserAccount>();
            _externalUserService.BindValid(externalUser);
            _externalUserService.BindLocalAccount(user, externalUser);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        [HttpPut("password")]
        [Api(Name = "更新密码", Perm = "user:profile:password:put")]
        public void UpdatePassword([FromBody] PasswordDto dto)
        {
            _userProfileService.UpdatePassword(dto);
        }

        /// <summary>
        /// 更新用户头像
        /// </summary>
        /// <param name="userDto"></param>
        /// <returns></returns>
        [HttpPut("avatar")]
        [Api(Name = "更新头像")]
        public async Task<string> UpdateAvatar([FromForm] IFormFile avatarfile)
        {
            var storePath = await _fileResourceService.LocalStorage(avatarfile, "wwwroot", "avatar");
            var url = _fileResourceService.MapToNetworkUrl(storePath);
            _userProfileService.UpdateAvatar(url);

            var account = _accountService.GetCurrent();
            _accountService.ClearCacheUser(account);
            return url;
        }

        ///// <summary>
        ///// 添加用户
        ///// </summary>
        //[ServiceFilter(typeof(TransactionFilter))]
        //public void Create([FromBody] UserDto userDto)
        //{
        //    var user = _userServices.Create(userDto);
        //    var password = _paramsService.GetValue(ParamsConstant.InitPassword);
        //    if (string.IsNullOrWhiteSpace(password)) ExceptionUtils.ThrowBusinessException($"系统参数:{ParamsConstant.InitPassword}，配置异常");
        //    _userServices.InitPassword(user.Id, password);
        //}

        ///// <summary>
        ///// 获取用户信息
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //[HttpGet("{id}")]
        //public SysUser Get([FromRoute] long id)
        //{
        //    return _userServices.GetUser(id);
        //}

        //[HttpDelete("{id}")]
        //public bool Delete([FromRoute] long id)
        //{
        //    var manageDepts = _departmentService.GetByManager(id);
        //    if (manageDepts != null && manageDepts.Count > 0)
        //        ExceptionUtils.ThrowBusinessException($"用户作为部门负责人无法删除：【{string.Join(',', manageDepts.Select(s => s.Name))}】");
        //    return _userServices.Delete(id);
        //}


    }
}
